<template>
  <div class="user-header">
    <el-button type="primary" @click="dialogVisible = true">新增</el-button>
    <el-form :inline="true">
      <el-form-item label="请输入">
        <el-input v-model="searchKey" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-card class="user-table">
    <el-table :data="userData" border stripe>
      <el-table-column v-for="lable in tableLable" :key="lable.prop" :width="lable.width" :prop="lable.prop"
                       :label="lable.label"></el-table-column>
      <el-table-column prop="action" label="操作">
        <template #="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete( scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        style="margin-top: 20px"
        background
        layout="->,prev, pager, next"
        :total="config.total"
        :page-size="10"
        :current-page="config.page"
        @current-change="handleCurrentChange"
    ></el-pagination>
  </el-card>
  <!--新增或编辑弹框-->
  <el-dialog :title="action === 'add' ? '新增用户' : '编辑用户'"
             v-model="dialogVisible" :before-close="handleClose">
    <el-form :inline="true"
             ref="ruleFormRef"
             :model="formData"
             :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model="formData.age"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="formData.sex">
              <el-radio label="1" value="1">男</el-radio>
              <el-radio label="0" value="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birth">
            <el-date-picker
                v-model="formData.birth"
                type="date"
                placeholder="选择日期"
                format="YYYY年MM月DD日"
                value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="地址" prop="addr">
            <el-input v-model="formData.addr"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: center">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitHandle">提交</el-button>
        </el-col>
      </el-row>


    </el-form>
  </el-dialog>
</template>
<script setup>

import { nextTick, onMounted, reactive, ref } from 'vue'
import { reqAddUser, reqDelteteUser, reqEditUser, reqUserList } from '@/api/user.js'
import { dayjs, ElMessage, ElMessageBox } from 'element-plus'

const userData = ref([])
const searchKey = ref('')
const config = ref({
  name: '',
  page: 1,
  total: 0,
})

const action = ref('add')
const dialogVisible = ref(false)
const formData = ref({
  name: '',
  age: '',
  sex: '',
  birth: '',
  addr: '',
})
const ruleFormRef = ref(null)
const rules = reactive({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'blur' },
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
  ],
  birth: [
    { required: true, message: '请选择日期', trigger: 'change' },
  ],
  addr: [
    { required: true, message: '请输入地址', trigger: 'blur' },
  ],
})
const submitHandle = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (action.value === 'add') {
          await reqAddUser(formData.value)
          ElMessage({
            message: '新增成功',
            type: 'success',
          })
        } else {
          await reqEditUser(formData.value)
          ElMessage({
            message: '编辑成功',
            type: 'success',
          })
        }
        dialogVisible.value = false
        getUserList()
     } catch (e) {
        ElMessage({
          message: '新增失败',
          type: 'error',
        })
      }
    }
  })
}
const handleClose = () => {
  dialogVisible.value = false
  //重置表单数据
  //formData.value = {}
}
const handleEdit = async (val) => {
  dialogVisible.value = true
  action.value = 'edit'
  nextTick(()=>{
    formData.value = {
      ...val,
      sex: val.sex === '男' ? '1' : '0',
    }
  })
  await reqEditUser(formData.value)
  getUserList()
}
onMounted(() => {
  getUserList()
})
const getUserList = async () => {
  const { data } = await reqUserList(config.value)
  userData.value = data.items.map(item => ({
    ...item,
    sex: item.sex === '1' ? '男' : '女',
  }))
  config.value.total = data.total
}
const handleSearch = () => {
  config.value.name = searchKey.value
  getUserList()

}
const handleCurrentChange = (page) => {
  config.value.page = page
  getUserList()
}
const handleDelete = (val) => {
  ElMessageBox.confirm('你确定要删除吗, 是否继续?').then(async () => {
    try {
      await reqDelteteUser({ id: val.id })
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
      getUserList()
    } catch (e) {
      ElMessage({
        message: '删除失败',
        type: 'error',
      })
    }
  })
}
const tableLable = reactive([
  {
    prop: 'name',
    label: '用户名',
    width: '100px',
  },
  {
    prop: 'age',
    label: '年龄',
    width: '100px',

  },
  {
    prop: 'sex',
    label: '性别',
    width: '100px',
  },
  {
    prop: 'birth',
    label: '出生日期',
    width: '200px',
  },
  {
    prop: 'addr',
    label: '地址'
  },
])
</script>

<style scoped lang="less">
.user-header {
  display: flex;
  justify-content: space-between;
}
</style>
